package com.jh.wdbc.service;

import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.jh.wdbc.model.ConnectionInfo;

@Service
public class DataBaseConnectionService {

	public ConnectionInfo getConnection(String name) throws Exception {
		ConnectionInfo connectionInfo = ConnectionManager.getConnection(name);

		if (!checkConnection(connectionInfo)) {
			ConnectionManager.reconect(connectionInfo);
		}
		return connectionInfo;
	}

	private boolean checkConnection(ConnectionInfo connectionInfo) {
		try {
			String query = "select 1";
			if (connectionInfo.getDbType().contains("ORACLE")) {
				query = "select 1 from dual";
			}

			Statement stmt = connectionInfo.getConnection().createStatement();
			stmt.executeQuery(query);
			stmt.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	public void destroy() throws Exception {
		ConnectionManager.destory();
	}

	public Set<String> getConnectionInfoHistory(HttpServletRequest request) {
		String value = null;
		if(request.getCookies() == null){
			return null;
		}
		
		for (Cookie cookie : request.getCookies()) {
			if (cookie.getName().equals("wdbc_history")) {
				value = cookie.getValue();
			}
		}

		if (value == null) {
			return null;
		}
		String[] dbs = value.split("\\|");
		Set<String> result = new HashSet<String>();
		for (String db : dbs) {
			if (StringUtils.isNotEmpty(db))
				result.add(db);
		}
		return result;
	}

	public ConnectionInfo getConnectionInfo(String name) throws Exception {
		List<ConnectionInfo> list = ConnectionManager.connections.getListForKey(name);
		if (list == null) {
			return ConnectionManager.getConnectionInfoFromDBPM(name);
		}
		return list.get(0);
	}

	@Scheduled(fixedDelay=20000) 
	public void connectionClear() throws SQLException {
		ConnectionManager.clear();
	}
}
